<template>
	<div class="warehouse-container base-page-container">
		<!-- 搜索区域 -->
		<common-search v-model="searchForm" :search-items="searchItemsConfig" @search="handleSearch"
			@reset="fetchTableData">
		</common-search>

		<!-- 操作按钮区域 -->
		<action-buttons 
			:buttons="{
				add: { visible: actionPermissions.add, order: 1, type: 'success' },
				enable: { visible: actionPermissions.enable, order: 2 },
				disable: { visible: actionPermissions.disable, order: 3 },
				delete: { visible: actionPermissions.delete, order: 4, type: 'danger' },
				import: { visible: actionPermissions.import, order: 5 },
				export: { visible: actionPermissions.export, order: 6 },
				viewLog: { visible: actionPermissions.viewLog, order: 7 },
				edit: { visible: false, order: 8 }
			}"
			:selected-data="selectedRows"
			:use-el-confirm="false"
			:no-confirm-buttons="['viewLog', 'export','delete']"
			@add="handleAdd"
			@export="handleExport" 
			@import="handleImport" 
			@enable="handleEnable" 
			@disable="handleDisable"
			@delete="handleDelete"
			@viewLog="handleViewLog"
		/>

		<!-- 表格区域 -->
		<custom-table
			:data="tableData"
			:columns="tableColumns"
			:loading="tableLoading"
			:current-page="pagination.currentPage"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			table-id="warehouse-table"
			@selection-change="handleSelectionChange"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
			<!-- 存储方式列的自定义插槽 -->
			<template #storageType="{ row }">
				<el-tag :type="row.storageType === '常温' ? 'success' : (row.storageType === '冷藏' ? 'warning' : 'danger')">
					{{ row.storageType }}
				</el-tag>
			</template>
			
			<!-- 状态列的自定义插槽 -->
			<template #status="{ row }">
				<el-tag :type="row.status === '启用' ? 'success' : 'info'">
					{{ row.status }}
				</el-tag>
			</template>
			
			<!-- 操作列 -->
			<template #operation="{ row }">
				<theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
				<theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
				<theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
			</template>
		</custom-table>

		<!-- 仓库信息弹窗 -->
		<el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增仓库' : '编辑仓库'" width="750px"
			destroy-on-close class="base-dialog" :close-on-click-modal="false">
			<el-form ref="warehouseFormRef" :model="warehouseForm" :rules="warehouseFormRules" label-width="80px"
				class="base-form">
				<div class="form-row">
					<el-form-item label="仓库编号" prop="code" required>
						<el-input v-model="warehouseForm.code" placeholder="请输入仓库编号"></el-input>
					</el-form-item>
					<el-form-item label="仓库名称" prop="name" required>
						<el-input v-model="warehouseForm.name" placeholder="请输入仓库名称"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="仓库地址" prop="region" required>
						<region-cascader v-model="warehouseForm.region" placeholder="请选择所在区域" :level="3" :separator="'/'"
							style="width: 100%" filterable clearable :use-code-data="false" :return-code="false" />
					</el-form-item>
				</div>

				<div class="form-row full-width">
					<el-form-item label="详细地址" prop="address" class="full-width-item">
						<el-input v-model="warehouseForm.address" placeholder="请输入详细地址，如街道、门牌号等" type="textarea" rows="3" ></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="邮编" prop="zipCode">
						<el-input v-model="warehouseForm.zipCode" placeholder="请输入邮编"></el-input>
					</el-form-item>
					<el-form-item label="联系人" prop="contactPerson">
						<el-input v-model="warehouseForm.contactPerson" placeholder="请输入联系人"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="固话" prop="telephone">
						<el-input v-model="warehouseForm.telephone" placeholder="请输入固话"></el-input>
					</el-form-item>
					<el-form-item label="手机号" prop="contactPhone">
						<el-input v-model="warehouseForm.contactPhone" placeholder="请输入手机号"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="存储方式" prop="storageType" required>
						<el-select v-model="warehouseForm.storageType" placeholder="请选择存储方式" style="width: 100%">
							<el-option label="常温" value="常温"></el-option>
							<el-option label="冷藏" value="冷藏"></el-option>
							<el-option label="冷冻" value="冷冻"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="状态" prop="status">
						<el-select v-model="warehouseForm.status" placeholder="请选择状态" style="width: 100%">
							<el-option label="启用" value="启用"></el-option>
							<el-option label="停用" value="停用"></el-option>
						</el-select>
					</el-form-item>
				</div>

				<div class="form-row full-width" style="border-bottom: solid 1px #eee;">
					<el-form-item label="备注" prop="remark" class="full-width-item">
						<el-input v-model="warehouseForm.remark" placeholder="请输入备注" type="textarea" rows="3"></el-input>
					</el-form-item>
				</div>
				
				<div class="form-row full-width">
					<el-form-item label="仓库策略" class="full-width-item">
						<div class="strategy-container">
							<div class="checkbox-row">
								<el-checkbox v-model="warehouseForm.allowPreAllocation">允许负库存（开启后，出库作业将不判断库存可用性）</el-checkbox>
							</div>
							<div class="checkbox-row">
								<el-checkbox v-model="warehouseForm.allowInventoryManagement">开启负仓位存管理（开启后，出入库作业需添入仓位）</el-checkbox>
							</div>
						</div>
					</el-form-item>
				</div>
				
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 日志弹窗 -->
		<log-dialog
			v-model:visible="logDialogVisible"
			:log-data="logData"
			:total="logPagination.total"
			:current-page="logPagination.currentPage"
			:page-size="logPagination.pageSize"
			@size-change="handleLogSizeChange"
			@current-change="handleLogCurrentChange"
		/>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		watch
	} from 'vue'
	import {
		useTheme
	} from '@/hooks/useTheme'
	import {
		RegionCascader,
		CustomTable
	} from '@/components/common'

	// 使用主题组合API
	const {
		themeType
	} = useTheme()

	// 判断是否开发环境
	const isDevelopment = computed(() => {
		return import.meta.env.MODE === 'development'
	})

	// 搜索项配置列表
	const searchItemsConfig = [{
			label: '仓库编号',
			prop: 'code',
			type: 'el-input',
			placeholder: '请输入仓库编号',
			defaultVisible: true
		},
		{
			label: '仓库名称',
			prop: 'name',
			type: 'el-input',
			placeholder: '请输入仓库名称',
			defaultVisible: true
		},
		{
			label: '状态',
			prop: 'status',
			type: 'el-select',
			placeholder: '请选择状态',
			defaultVisible: true,
			options: [{
					label: '请选择状态',
					value: ''
				},
				{
					label: '启用',
					value: '启用'
				},
				{
					label: '停用',
					value: '停用'
				}
			]
		},
		// {
		// 	label: '存储方式',
		// 	prop: 'storageType',
		// 	type: 'el-select',
		// 	placeholder: '请选择存储方式',
		// 	defaultVisible: true,
		// 	options: [{
		// 			label: '请选择存储方式',
		// 			value: ''
		// 		},
		// 		{
		// 			label: '常温',
		// 			value: '常温'
		// 		},
		// 		{
		// 			label: '冷藏',
		// 			value: '冷藏'
		// 		},
		// 		{
		// 			label: '冷冻',
		// 			value: '冷冻'
		// 		}
		// 	]
		// },
		// {
		// 	label: '所在地区',
		// 	prop: 'regionSearch',
		// 	type: 'region-cascader',
		// 	placeholder: '请选择所在地区',
		// 	defaultVisible: false,
		// 	level: 3,
		// 	separator: '/',
		// 	useCodeData: false,
		// 	returnCode: false,
		// 	filterable: true,
		// 	clearable: true
		// },
		// {
		// 	label: '联系人',
		// 	prop: 'contactPerson',
		// 	type: 'el-input',
		// 	placeholder: '请输入联系人',
		// 	defaultVisible: false
		// },
		// {
		// 	label: '联系电话',
		// 	prop: 'contactPhone',
		// 	type: 'el-input',
		// 	placeholder: '请输入联系电话',
		// 	defaultVisible: false
		// },
		// {
		// 	label: '创建日期',
		// 	prop: 'createDate',
		// 	type: 'el-date-picker',
		// 	placeholder: '请选择创建日期',
		// 	defaultVisible: false,
		// 	dateType: 'date',
		// 	format: 'YYYY-MM-DD',
		// 	valueFormat: 'YYYY-MM-DD'
		// }
	]

	// 操作按钮权限
	const actionPermissions = ref({
		add: true,
		export: false,
		import: false,
		enable: true,
		disable: true,
		viewLog:true,
		delete:true,
		edit:false
	})

	// 表格操作权限
	const tablePermissions = ref({
		edit: true,
		view: true,
		log: true
	})

	// 搜索表单数据
	const searchForm = reactive({
		code: '',
		name: '',
		status: '',
		storageType: '',
		regionSearch: '',
		contactPerson: '',
		contactPhone: '',
		createDate: ''
	})

	// 表格数据相关
	const tableData = ref([])
	const tableLoading = ref(false)
	const selectedRows = ref([])

	// 分页相关
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 仓库表单相关
	const warehouseFormRef = ref(null)
	const dialogVisible = ref(false)
	const dialogType = ref('add') // 'add' 或 'edit'
	const warehouseForm = reactive({
		id: '',
		code: '',
		name: '',
		region: '',
		address: '',
		zipCode: '',
		contactPerson: '',
		contactPhone: '',
		telephone: '',
		storageType: '常温',
		status: '启用',
		allowPreAllocation: false,
		allowInventoryManagement: false,
		remark: ''
	})

	// 表单校验规则
	const warehouseFormRules = {
		code: [{
			required: true,
			message: '请输入仓库编号',
			trigger: 'blur'
		}],
		name: [{
			required: true,
			message: '请输入仓库名称',
			trigger: 'blur'
		}],
		region: [{
			required: true,
			message: '请选择所在区域',
			trigger: 'change'
		}],
		storageType: [{
			required: true,
			message: '请选择存储方式',
			trigger: 'change'
		}]
	}

	// 监听region字段变化
	watch(() => warehouseForm.region, (newVal) => {
		console.log('仓库地址变化:', newVal);
	}, { immediate: true });

	// 日志弹窗相关
	const logDialogVisible = ref(false)
	const logData = ref([])
	const logPagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 表格列配置
	const tableColumns = ref([
		{ prop: 'code', label: '仓库编号', width: '100', minWidth: '100', visible: true },
		{ prop: 'name', label: '仓库名称', width: '150', minWidth: '150', visible: true },
		{ prop: 'storageType', label: '存储方式', width: '120', minWidth: '120', visible: true },
		{ prop: 'status', label: '状态', width: '80', minWidth: '80', visible: true },
		{ prop: 'contactPerson', label: '联系人', width: '100', minWidth: '100', visible: true },
		{ prop: 'contactPhone', label: '手机号', width: '120', minWidth: '120', visible: true },
		{ prop: 'address', label: '仓库地址', minWidth: '180', visible: true },
		{ prop: 'createdBy', label: '创建人', width: '100', minWidth: '100', visible: true },
		{ prop: 'createdTime', label: '创建时间', width: '160', minWidth: '160', visible: true },
		{ prop: 'updatedBy', label: '修改人', width: '100', minWidth: '100', visible: true },
		{ prop: 'updatedTime', label: '修改时间', width: '160', minWidth: '160', visible: true },
		{ prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
	])

	// 获取表格数据
	const fetchTableData = async () => {
		tableLoading.value = true

		try {
			// 模拟异步请求
			if (isDevelopment.value) {
				setTimeout(() => {
					// 模拟数据
					tableData.value = [{
							id: '1',
							code: '005',
							name: '华东杭州分仓',
							storageType: '常温',
							status: '启用',
							contactPerson: '小李',
							contactPhone: '15889896789',
							telephone: '0571-88889999',
							zipCode: '310000',
							allowPreAllocation: true,
							allowInventoryManagement: false,
							address: '浙江省杭州市西湖区XXXXX',
							createdBy: '小李',
							createdTime: '2024-11-02 10:23:10',
							updatedBy: '小李', 
							updatedTime: '2024-11-02 10:23:10',
							remark: ''
						},
						{
							id: '2',
							code: '004',
							name: '华东苏州分仓',
							storageType: '冷藏',
							status: '启用',
							contactPerson: '小张',
							contactPhone: '15789896789',
							telephone: '0512-66667777',
							zipCode: '215000',
							allowPreAllocation: false,
							allowInventoryManagement: true,
							address: '江苏省苏州市XXXXX',
							createdBy: '小李',
							createdTime: '2024-11-01 20:03:27',
							updatedBy: '小李',
							updatedTime: '2024-11-01 20:03:27',
							remark: ''
						},
						{
							id: '3',
							code: '003',
							name: '华北上海分仓',
							storageType: '冷冻',
							status: '启用',
							contactPerson: '小王',
							contactPhone: '15689896789',
							telephone: '021-55556666',
							zipCode: '200000',
							allowPreAllocation: true,
							allowInventoryManagement: true,
							address: '上海市虹口区XXXXX',
							createdBy: '小李',
							createdTime: '2024-10-20 17:47:10',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:47:10',
							remark: ''
						},
						{
							id: '4',
							code: '002',
							name: '华北北京分仓',
							storageType: '常温',
							status: '启用',
							contactPerson: '小赵',
							contactPhone: '15589896789',
							telephone: '010-33334444',
							zipCode: '100000',
							allowPreAllocation: false,
							allowInventoryManagement: false,
							address: '北京市西城区XXXXX',
							createdBy: '小李',
							createdTime: '2024-10-20 17:46:17',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:46:17',
							remark: ''
						},
						{
							id: '5',
							code: '001',
							name: '华北石家庄分仓',
							storageType: '常温',
							status: '停用',
							contactPerson: '小钱',
							contactPhone: '15989896789',
							telephone: '0311-22223333',
							zipCode: '050000',
							allowPreAllocation: false,
							allowInventoryManagement: true,
							address: '河北省石家庄市XXXXX',
							createdBy: '小李',
							createdTime: '2024-10-20 17:45:42',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:45:42',
							remark: ''
						}
					]

					pagination.total = 5 // 模拟总数据量
					tableLoading.value = false
				}, 500)
			} else {
				// 实际环境API调用
				// const res = await api.getWarehouseList({
				//   page: pagination.currentPage,
				//   pageSize: pagination.pageSize,
				//   ...searchForm
				// })
				// tableData.value = res.data.list
				// pagination.total = res.data.total
				tableLoading.value = false
			}
		} catch (error) {
			console.error('获取仓库列表失败', error)
			tableLoading.value = false
		}
	}

	// 处理分页大小变化
	const handleSizeChange = (size) => {
		pagination.pageSize = size
		fetchTableData()
	}

	// 处理当前页变化
	const handleCurrentChange = (page) => {
		pagination.currentPage = page
		fetchTableData()
	}

	// 处理表格选择事件
	const handleSelectionChange = (rows) => {
		selectedRows.value = rows
	}

	// 处理搜索
	const handleSearch = () => {
		pagination.currentPage = 1

		// 处理搜索条件，构建API请求参数
		const params = {
			...searchForm
		};

		// 如果有地区搜索，需要特殊处理
		if (params.regionSearch) {
			// 根据项目需求，可能需要从字符串中提取省市区信息
			// 例如: "浙江省/杭州市/西湖区" => { province: "浙江省", city: "杭州市", district: "西湖区" }
			const regions = params.regionSearch.split('/');
			if (regions.length > 0) params.province = regions[0];
			if (regions.length > 1) params.city = regions[1];
			if (regions.length > 2) params.district = regions[2];
		}

		// 移除不需要的属性
		delete params.regionSearch;

		console.log('搜索参数:', params);

		// 调用获取数据函数
		fetchTableData();
	}

	// 处理添加仓库
	const handleAdd = () => {
		dialogType.value = 'add'
		dialogVisible.value = true
		// 清空表单
		Object.keys(warehouseForm).forEach(key => {
			if (key === 'storageType') {
				warehouseForm[key] = '常温'
			} else if (key === 'status') {
				warehouseForm[key] = '启用'
			} else if (key === 'allowPreAllocation' || key === 'allowInventoryManagement') {
				warehouseForm[key] = false
			} else {
				warehouseForm[key] = ''
			}
		})
	}

	// 处理编辑仓库
	const handleEdit = (row) => {
		dialogType.value = 'edit'
		dialogVisible.value = true

		// 填充表单数据
		Object.keys(warehouseForm).forEach(key => {
			if (key === 'region') {
				// 处理region字段，获取省市区信息
				// 可以从address字段中提取，或者直接使用单独存储的region字段
				if (row.region) {
					// 如果数据库已存储省市区信息，直接使用
					warehouseForm.region = row.region;
				} else if (row.address) {
					// 如果没有独立存储省市区信息，尝试从地址中提取
					// 这里假设地址格式为：省/市/区 详细地址
					const addressParts = row.address.split(' ');
					if (addressParts.length > 0) {
						const regionPart = addressParts[0];
						// 检查是否包含省市区格式（简单判断是否包含分隔符"/"）
						if (regionPart.includes('/')) {
							warehouseForm.region = regionPart;
							// 详细地址可能需要更新为剩余部分
							if (addressParts.length > 1) {
								warehouseForm.address = addressParts.slice(1).join(' ');
							}
						} else {
							warehouseForm.region = '';
							warehouseForm.address = row.address;
						}
					} else {
						warehouseForm.region = '';
						warehouseForm.address = row.address;
					}
				} else {
					warehouseForm.region = '';
				}
			} else {
				warehouseForm[key] = row[key] || '';
			}
		});
	}

	// 处理查看仓库
	const handleView = (row) => {
		// 实现查看逻辑...
		console.log('查看仓库', row)
	}

	// 处理日志
	const handleLog = (row) => {
		logDialogVisible.value = true

		// 模拟日志数据
		setTimeout(() => {
			logData.value = [{
					operateTime: '2024-01-05 14:30:25',
					operator: '小李',
					operateContent: `修改了仓库 ${row.name} 的联系电话`
				},
				{
					operateTime: '2023-12-20 09:15:36',
					operator: '小王',
					operateContent: `修改了仓库 ${row.name} 的地址信息`
				},
				{
					operateTime: '2023-11-15 16:42:10',
					operator: '小张',
					operateContent: `创建了仓库 ${row.name}`
				}
			]
			logPagination.total = 3
		}, 300)
	}

	// 处理日志分页变化
	const handleLogSizeChange = (size) => {
		logPagination.pageSize = size
		// 重新获取日志数据
	}

	const handleLogCurrentChange = (page) => {
		logPagination.currentPage = page
		// 重新获取日志数据
	}

	// 处理导出
	const handleExport = () => {
		console.log('导出仓库数据')
	}

	// 处理导入
	const handleImport = () => {
		console.log('导入仓库数据')
	}

	// 处理启用
	const handleEnable = () => {
		console.log('启用仓库', selectedRows.value)
		
		// 模拟API请求
		setTimeout(() => {
			ElMessage.success('启用成功')
			fetchTableData()
		}, 500)
	}

	// 处理停用
	const handleDisable = () => {
		console.log('停用仓库', selectedRows.value)
		
		// 模拟API请求
		setTimeout(() => {
			ElMessage.success('停用成功')
			fetchTableData()
		}, 500)
	}

	// 处理删除
	const handleDelete = () => {
		console.log('删除仓库', selectedRows.value)
		
		// 模拟API请求
		setTimeout(() => {
			ElMessage.success('删除成功')
			fetchTableData()
		}, 500)
	}

	// 处理查看日志
	const handleViewLog = () => {
		handleLog(selectedRows.value[0])
	}

	// 提交表单
	const submitForm = async () => {
		warehouseFormRef.value.validate(async (valid) => {
			if (valid) {
				// 构建完整地址
				let fullAddress = '';
				if (warehouseForm.region) {
					fullAddress += warehouseForm.region + ' ';
				}
				if (warehouseForm.address) {
					fullAddress += warehouseForm.address;
				}

				// 构建提交数据
				const submitData = {
					...warehouseForm,
					// 完整地址（用于显示）
					fullAddress: fullAddress.trim(),
					// 省市区的值已经由组件处理成了字符串，直接使用
				};

				console.log('提交表单', submitData);

				try {
					// 模拟提交
					setTimeout(() => {
						ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
						dialogVisible.value = false;
						fetchTableData();
					}, 500);
				} catch (error) {
					console.error('提交表单失败', error);
				}
			}
		});
	}

	// 页面初始化
	onMounted(() => {
		fetchTableData()
	})
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
.strategy-container {
	margin-top: 5px;
	
	.checkbox-row {
		margin-bottom: 10px;
		
		&:last-child {
			margin-bottom: 0;
		}
	}
}
</style>